package com.itheima.controller;


import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.health.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class checkItemController {

    //注入service进来
    @Autowired
    private CheckItemService service;

    @PostMapping("/checkItem")//新增检查项
    public Result add(@RequestBody CheckItem checkItem) {
        System.out.println("checkItem = " + checkItem);

        //调用service
        int rows = service.add(checkItem);

        //判断
        Result result = null;
        if (rows > 0) {
            //新增成功
            result = new Result(true, MessageConstant.ADD_CHECKITEM_SUCCESS);
        } else {
            //新增失败
            result = new Result(false, MessageConstant.ADD_CHECKITEM_FAIL);
        }
        //返回
        return result;
    }

    @GetMapping("/checkItem/{param}")//分页查询
    public Result add(@PathVariable String param) {

        try {
            //调用service
            PageResult<CheckItem> pageResult = service.findPage(JSON.parseObject(param, QueryPageBean.class));

            //响应成功
            return new Result(true, MessageConstant.QUERY_CHECKITEM_SUCCESS, pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            //响应失败
            return new Result(false, MessageConstant.QUERY_CHECKITEM_FAIL);
        }
    }

    @DeleteMapping("/checkItem/{id}")//删除检查项
    public Result delete(@PathVariable int id) {
        //调用方法
        int rows = service.delete(id);

        //判断
        Result result = null;
        if (rows > 0) {
            //删除成功
            result = new Result(true, MessageConstant.DELETE_CHECKITEM_SUCCESS);
        } else {
            //删除失败
            result = new Result(false, MessageConstant.DELETE_CHECKITEM_FAIL);
        }
        //返回结果
        return result;
    }

    @PutMapping("checkItemUP")
    public Result update(@RequestBody CheckItem checkItem) {

        //调用方法
        int rows = service.update(checkItem);

        //判断
        Result result = null;
        if (rows > 0) {
            result = new Result(true, MessageConstant.EDIT_CHECKITEM_SUCCESS);
        } else {
            result = new Result(false, MessageConstant.EDIT_CHECKITEM_FAIL);
        }
        return result;
    }


}
